package com.iwomy.secureplat.platform.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iwomy.secureplat.common.core.exception.PlatformBizErrorCodes;
import com.iwomy.secureplat.common.core.util.MsgUtils;
import com.iwomy.secureplat.common.core.util.R;
import com.iwomy.secureplat.common.log.annotation.SysLog;
import com.iwomy.secureplat.common.security.util.SecurityUtils;
import com.iwomy.secureplat.platform.dto.BasicDeviceModelDTO;
import com.iwomy.secureplat.platform.entity.BasicAuthorizationRecordEntity;
import com.iwomy.secureplat.platform.entity.BasicDeviceEntity;
import com.iwomy.secureplat.platform.entity.BasicDeviceModelEntity;
import com.iwomy.secureplat.platform.exception.PlatformException;
import com.iwomy.secureplat.platform.service.BasicAuthorizationRecordService;
import com.iwomy.secureplat.platform.service.BasicDeviceModelService;
import com.iwomy.secureplat.platform.service.BasicDeviceService;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import com.iwomy.secureplat.common.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 设备型号表
 *
 * @author pig
 * @date 2023-11-14 14:43:58
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/basicDeviceModel")
@Tag(description = "basicDeviceModel", name = "设备型号表管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
@Slf4j
public class BasicDeviceModelController {

	private final BasicDeviceModelService basicDeviceModelService;

	private final BasicAuthorizationRecordService basicAuthorizationRecordService;

	private final RedisTemplate<String, Object> redisTemplate;

	private final BasicDeviceService basicDeviceService;

	/**
	 * 分页查询
	 *
	 * @param page                分页对象
	 * @param basicDeviceModelDTO 设备型号表
	 * @return
	 */
	@Operation(summary = "分页查询", description = "分页查询")
	@GetMapping("/page")
	@PreAuthorize("@pms.hasPermission('platform_basicDeviceModel_view')")
	public R getBasicDeviceModelPage(@ParameterObject Page page, @ParameterObject BasicDeviceModelDTO basicDeviceModelDTO) {
		return R.ok(basicDeviceModelService.getBasicDeviceModelPage(page, basicDeviceModelDTO));
	}

	/**
	 * 分页查询
	 *
	 * @param page                分页对象
	 * @param basicDeviceModelDTO 产品库
	 * @return
	 */
	@Operation(summary = "分页查询", description = "分页查询")
	@GetMapping("/basicDeviceStock")
	@PreAuthorize("@pms.hasPermission('platform_basicDeviceStock_view')")
	public R gebasicDeviceStock(@ParameterObject Page page, @ParameterObject BasicDeviceModelDTO basicDeviceModelDTO) {
		return R.ok(basicDeviceModelService.getBasicDeviceModelPage(page, basicDeviceModelDTO));
	}


	/**
	 * 通过id查询设备型号表
	 *
	 * @param id id
	 * @return R
	 */
	@Operation(summary = "通过id查询", description = "通过id查询")
	@GetMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('platform_basicDeviceModel_view')")
	public R getById(@PathVariable("id") Long id) {
		return R.ok(basicDeviceModelService.getDeviceModelById(id));
	}

	/**
	 * 新增设备型号表
	 *
	 * @param basicDeviceModel 设备型号表
	 * @return R
	 */
	@Operation(summary = "新增设备型号表", description = "新增设备型号表")
	@SysLog("新增设备型号表")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('platform_basicDeviceModel_add')")
	public R save(@RequestBody BasicDeviceModelEntity basicDeviceModel) {
		BasicDeviceModelEntity wrapperEntity = new BasicDeviceModelEntity();
		wrapperEntity.setDeviceModelName(basicDeviceModel.getDeviceModelName());
		wrapperEntity.setDeviceTypeId(basicDeviceModel.getDeviceTypeId());
		LambdaQueryWrapper<BasicDeviceModelEntity> wrapper = Wrappers.lambdaQuery(wrapperEntity);
		BasicDeviceModelEntity one = basicDeviceModelService.getOne(wrapper);
		if (ObjectUtil.isNotNull(one)) {
//			throw new PlatformException("设备型号已存在");
			throw new PlatformException(MsgUtils.getMessage(PlatformBizErrorCodes.DEVICEMODEL_ID_EXIST));
		}
		basicDeviceModel.setDeptId(SecurityUtils.getUser().getDeptId());
		return R.ok(basicDeviceModelService.save(basicDeviceModel));
	}

	/**
	 * 修改设备型号表
	 *
	 * @param basicDeviceModel 设备型号表
	 * @return R
	 */
	@Operation(summary = "修改设备型号表", description = "修改设备型号表")
	@SysLog("修改设备型号表")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('platform_basicDeviceModel_edit')")
	public R updateById(@RequestBody BasicDeviceModelEntity basicDeviceModel) {
		long count = basicAuthorizationRecordService.count(Wrappers.<BasicAuthorizationRecordEntity>lambdaQuery().eq(BasicAuthorizationRecordEntity::getDeviceModelId, basicDeviceModel.getId()));
		long count2 = basicDeviceService.count(Wrappers.<BasicDeviceEntity>lambdaQuery().eq(BasicDeviceEntity::getDeviceModelId, basicDeviceModel.getId()));

		if (count > 0 || count2 > 0)
//			return R.failed("设备型号已被使用不允许修改");
			return R.failed(MsgUtils.getMessage(PlatformBizErrorCodes.DEVICEMODEL_ID_USED_MODIFY));

		BasicDeviceModelEntity wrapperEntity = new BasicDeviceModelEntity();
		wrapperEntity.setDeviceModelName(basicDeviceModel.getDeviceModelName());
		LambdaQueryWrapper<BasicDeviceModelEntity> wrapper = Wrappers.lambdaQuery(wrapperEntity);
		BasicDeviceModelEntity one = basicDeviceModelService.getOne(wrapper);
		if (ObjectUtil.isNotNull(one) && !one.getId().equals(basicDeviceModel.getId())) {
//			throw new PlatformException("设备型号已存在");
			throw new PlatformException(MsgUtils.getMessage(PlatformBizErrorCodes.DEVICEMODEL_ID_EXIST));
		}
		return R.ok(basicDeviceModelService.updateById(basicDeviceModel));
	}

	/**
	 * 启用禁用
	 *
	 * @param basicDeviceModel 设备型号
	 * @return R
	 */
	@Operation(summary = "启用禁用设备型号", description = "启用禁用设备型号")
	@SysLog(expression = "'启用禁用设备型号'.concat(#basicDeviceModel.remarks)")
	@PutMapping("/enableOrDisable")
	@PreAuthorize("@pms.hasPermission('platform_basicDeviceModel_enableOrDisable')")
	public R enableOrDisable(@RequestBody BasicDeviceModelDTO basicDeviceModel) {

		BasicDeviceModelEntity basicDeviceModelEntity = new BasicDeviceModelEntity();
		basicDeviceModelEntity.setId(basicDeviceModel.getId());
		basicDeviceModelEntity.setRemarks(basicDeviceModel.getRemarks());
		basicDeviceModelEntity.setState(basicDeviceModel.getState());
		return R.ok(basicDeviceModelService.updateById(basicDeviceModelEntity));
	}

	/**
	 * 通过id删除设备型号表
	 *
	 * @param ids id列表
	 * @return R
	 */
	@Operation(summary = "通过id删除设备型号表", description = "通过id删除设备型号表")
	@SysLog("通过id删除设备型号表")
	@DeleteMapping
	@PreAuthorize("@pms.hasPermission('platform_basicDeviceModel_del')")
	public R removeById(@RequestBody Long[] ids) {
		long count = basicAuthorizationRecordService.count(Wrappers.<BasicAuthorizationRecordEntity>lambdaQuery().in(BasicAuthorizationRecordEntity::getDeviceModelId, ids));
		long count2 = basicDeviceService.count(Wrappers.<BasicDeviceEntity>lambdaQuery().in(BasicDeviceEntity::getDeviceModelId, ids));

		if (count > 0 || count2 > 0)
//			return R.failed("设备型号已被使用不允许删除");
			return R.failed(MsgUtils.getMessage(PlatformBizErrorCodes.DEVICEMODEL_ID_USED_DELETE));
		return R.ok(basicDeviceModelService.removeBatchByIds(CollUtil.toList(ids)));
	}


	/**
	 * 导出excel 表格
	 *
	 * @param basicDeviceModel 查询条件
	 * @param ids              导出指定ID
	 * @return excel 文件流
	 */
	@ResponseExcel
	@GetMapping("/export")
	@PreAuthorize("@pms.hasPermission('platform_basicDeviceModel_export')")
	public List<BasicDeviceModelEntity> export(BasicDeviceModelEntity basicDeviceModel, Long[] ids) {
		return basicDeviceModelService.list(Wrappers.lambdaQuery(basicDeviceModel).in(ArrayUtil.isNotEmpty(ids), BasicDeviceModelEntity::getId, ids));
	}

	/**
	 * 分页查询
	 *
	 * @param basicDeviceModel 设备类型
	 * @return
	 */
	@Operation(summary = "分页查询", description = "分页查询")
	@GetMapping("/list")
//	@PreAuthorize("@pms.hasPermission('platform_basicDeviceModel_view')" )
	public R getBasicDeviceModelList(@ParameterObject BasicDeviceModelEntity basicDeviceModel) {
		return R.ok(basicDeviceModelService.getDeviceModelList(basicDeviceModel));
	}

	/**
	 * 验证码
	 *
	 * @return
	 */
	@GetMapping("/captcha")
	public R captcha() throws Exception {
		SpecCaptcha captcha = new SpecCaptcha(130, 48, 4);
		captcha.setCharType(Captcha.TYPE_ONLY_CHAR);
		redisTemplate.opsForValue().set("captcha", captcha.text().toLowerCase(), 600, TimeUnit.SECONDS);
		String codeImg = captcha.toBase64();
		log.info("验证码是:{}" + captcha.text());
		Map<String, String> captchaMap = new HashMap<>();
		captchaMap.put("codeImg", codeImg);
		captchaMap.put("text", captcha.text());
		return R.ok(captchaMap);
	}

	/**
	 * 授权
	 *
	 * @param basicDeviceModelDTO 实体
	 */
	@SysLog("授权")
	@GetMapping("/authorize")
	public R authorize(@ParameterObject BasicDeviceModelDTO basicDeviceModelDTO) {
		String captchaValue = (String) redisTemplate.opsForValue().get("captcha");
		log.info("验证码是:{}" + captchaValue);
		log.info("用户输入的验证码是:{}" + basicDeviceModelDTO.getCode().toLowerCase());
		if (captchaValue != null && captchaValue.equals(basicDeviceModelDTO.getCode().toLowerCase())) {
			return basicDeviceModelService.authorize(basicDeviceModelDTO);
		} else {
			return R.failed("验证码校验不通过");
		}
	}
}